<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\facade\Cache;

/**
 * 标签管理
 */
class Tags extends Backend
{
    /**
     * Tags模型对象
     * @var object
     * @phpstan-var \app\common\model\Tags
     */
    protected object $model;

    protected string|array $defaultSortField = 'weigh,desc';

    protected array|string $preExcludeFields = ['id', 'create_time'];

    protected string|array $quickSearchField = ['id','string','type'];

    public function initialize(): void
    {
        parent::initialize();
        $this->model = new \app\common\model\Tags;
    }

    /**
     * 查看
     * @throws Throwable
     */
    public function index(): void
    {

        if ($this->request->param('select')) {
            $this->select();
        }

        $this->request->param('type');
        $type = $this->request->param('type');
        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $map=[];
        if ($type) {
            $map[] = ['type', '=', $type];
        }
        $pid = $this->request->param('pid',0);
        $map[] = ['pid', '=', $pid];
        $res = $this->model
            ->field($this->indexField)
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)
            ->where($map)
            ->order($order)
            ->paginate($limit)->each(function ($item){
                $parent_name=$this->model->where('id',$item['pid'])->cache(true)->value('string','-');
                $item['parent_name']=$parent_name?$parent_name:'-';
                $item['children']=$this->model->where('pid',$item['id'])->cache(true)->select();
            });;
        $this->success('', [
            'list'   => $res->items(),
            'total'  => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }

    /**
     * 若需重写查看、编辑、删除等方法，请复制 @see \app\admin\library\traits\Backend 中对应的方法至此进行重写
     */
}
